<?php
//开户会话
session_start();
include_once "conn.php";
$sql = "select * from userinfo where username = '" . $_POST['username'] . "' and pw = '" . md5($_POST['pw']) . "'";
$remember = isset($_POST['remember']) ? 1 : 0;
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result)) {
    //说明找到了，登录成功
    //print_r($result);
    //exit;

    $info = mysqli_fetch_array($result, MYSQLI_ASSOC);  //只取关联数组
    //print_r($info);  //索引数组、关联数组
    //exit;
    //保存登录信息
    /*$sql = "insert into log (userID, loggedTime, ip) VALUES ('" . $info['id'] . "','" . time() . "','".get_real_ip()."')";
    mysqli_query($conn,$sql);
    */
    if ($info['isAdmin']) {  //说明是管理员
        $_SESSION['admin'] = 1;
    } else { //说明是普通用户
        $_SESSION['admin'] = 0;
    }
    echo "<script>alert('登录成功');location.href='index.php';</script>";
    $_SESSION['logged'] = 1;
    $_SESSION['username'] = $_POST['username'];
    $_SESSION['loggedID'] = $info['id'];
    //判断是否要保存登录
    if($remember){
        //写入cookie
        setcookie('hasLoggedUsername',$_POST["username"],time()+3600*24*7);  //设置了一个名字叫hasLogged的cookie，其值为当前登录者的用户名，有效期为一周
        setcookie('isAdmin',$_SESSION['admin'],time()+3600*24*7);
    }
    else{
        setcookie('hasLoggedUsername',0,time()-1000);  //设置当前cookie到期时间为现在之前 ，即使其过期
        setcookie('isAdmin',0,time()-1000);
    }
    //var_dump($_COOKIE['hasLoggedUsername']);
} else {
    //说明没找到，登录失败
    $_SESSION['logged'] = 0;
    $_SESSION['username'] = '';
    $_SESSION['loggedID'] = 0;
    $_SESSION['admin'] = 0;
    echo "<script>alert('错误的用户名和（或）密码错误');history.back();</script>";
}

function get_real_ip(){
    $ip = FALSE;
    //客户端IP 或 NONE
    if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    }
    //多重代理服务器下的客户端真实IP地址（可能伪造）,如果没有使用代理，此字段为空
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
        if ($ip) {
            array_unshift($ips, $ip);
            $ip = FALSE;
        }
        for ($i = 0; $i < count($ips); $i++) {
            if (!eregi("^(10│172.16│192.168).", $ips[$i])) {
                $ip = $ips[$i];
                break;
            }
        }
    }
    //客户端IP 或 (最后一个)代理服务器 IP
    return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}
